package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import bean.Locale;

@ManagedBean(name="daoLocali")
@ApplicationScoped
public class DaoLocali extends Dao {
	ArrayList<Locale> locali;
	
	public ArrayList<Locale> getLocali() throws DaoException, NotFoundException{
		locali = new ArrayList<Locale>();
		ResultSet rs = null;

		String query = 
				"SELECT * " +
						"FROM " + Locale.TABLE_NAME;
		;
		try {
			rs = st.executeQuery(query);
			log.log(3, this.getClass() + ".Execution: " + query);
		} catch (SQLException e) {
			throw new DaoException(this.getClass() + ".Error executing query: " + query);
		}

		try {
			int colNum = rs.getMetaData().getColumnCount();
			HashMap<String, String> line;
			Locale locale;

			while (rs.next()) {
				line = new HashMap <String, String>();
				for (int i = 1; i <= colNum; i++)
				{
					line.put(rs.getMetaData().getColumnLabel(i), rs.getString(i));
				}

				locale = new Locale(line);
				locali.add(locale);
			}

			if (locali.isEmpty())
				throw new NotFoundException(this.getClass() + ". No locals found");
		} catch (SQLException e) {
			throw new DaoException(this.getClass() + ".Error getting locals from Database");
		}

		return locali;
	}

	public boolean insertLocale(Locale locale) throws DuplicateException, DaoException{
		boolean result = false;

		if (locali != null )
		{
			for (Locale l : locali)
			{
				if (locale.getName().equals(l.getName()))
					throw new DuplicateException("Local already in table");
			}
		}
		
		StringBuilder query = new StringBuilder();
		query.append("INSERT INTO " + Locale.TABLE_NAME  + " (" + 
				Locale.NAME_COL + ", " + 
				Locale.TYPE_COL + ", " + 
				Locale.DESC_COL + ", " + 
				Locale.ADDRESS_COL + ", " + 
				Locale.IMAGE_COL + ")"); 
		query.append("VALUES (" +
				"'" + locale.getName() + "', " +
				"'" + locale.getType() + "', " +
				"'" + locale.getDesc() + "', " +
				"'" + locale.getAddress() + "', " +
				"'" + locale.getImage() + "'); ");

		try {
			result = st.execute(query.toString());
			result = true;
		} catch (SQLException e) {
			throw new DaoException( this.getClass() + ".Error getting locals from Database. " + query);
		}

		return result;
	}

	public void delete(String id) throws DaoException {
		StringBuilder query = new StringBuilder();
		query.append("DELETE FROM " + Locale.TABLE_NAME  + " ");
		query.append("WHERE " + Locale.ID_COL + " = " + id);

		try {
			st.execute(query.toString());
			log.log(3, this.getClass() + ". Executed: " + query);
		} catch (SQLException e) {
			throw new DaoException(this.getClass() + ". Error deleting locale from Database. " + query);
		}
	}

	public boolean modify(Locale locale) {
		// TODO Auto-generated method stub
		return false;
	}
}